/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ee.aop;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.apache.log4j.Logger;

/**
 *
 * @author Gabriel Bran <gbran.u@gmail.com>
 */
@Loggable
@Interceptor
public class LoggerInterceptor {

    @Inject
    private transient Logger logger;

    @AroundInvoke
    public Object log(InvocationContext invocationContext) throws Exception {
        try {
            logger.info(">>> EJECUTANDO ".concat(invocationContext.getMethod().getDeclaringClass() + "." + invocationContext.getMethod().getName()));
            return invocationContext.proceed();
        } catch (Exception e) {
            String methodDef = ">>> ERROR AL EJECUTAR " + invocationContext.getMethod().getDeclaringClass() + "." + invocationContext.getMethod().getName();
            if (!invocationContext.getMethod().isAnnotationPresent(LoggerSeverity.class)) {
                logger.info("Error al invocar: ".concat(methodDef), e);
            } else {
                LoggerSeverity severity = invocationContext.getMethod().getAnnotation(LoggerSeverity.class);
                switch (severity.level()) {
                    case INFORMATION:
                        logger.info("Error al invocar: ".concat(methodDef), e);
                        break;
                    case WARNING:
                        logger.warn("Error al invocar: ".concat(methodDef), e);
                        break;
                    case ERROR:
                        logger.error("Error al invocar: ".concat(methodDef), e);
                        break;
                }
            }
        } finally {
            return invocationContext.proceed();
        }
    }
}
